<template>
  <div class="addChart">
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-button type="primary" @click="uploadHandle()">上传文件</el-button>
      <el-form-item v-if="dataForm.image" label="图片预览" prop="image">
        <el-image
          style="width: 100px; height: 100px; margin-bottom:-4px"
          :src="dataForm.image"
        >
        </el-image>
      </el-form-item>
      <el-form-item label="轮播图片" prop="image">
      <el-input v-model="dataForm.image" placeholder="轮播图片"></el-input>
    </el-form-item>
    <el-form-item label="序号" prop="num">
      <el-input v-model="dataForm.num" placeholder="序号"></el-input>
    </el-form-item>
    <el-form-item label="状态（0：不启用，1启用）" prop="status">
      <el-input v-model="dataForm.status" placeholder="状态（0：不启用，1启用）"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false,dataForm.image = null">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
    <el-dialog
      v-if="uploadVisible"
      title="上传文件"
      :close-on-click-modal="false"
      @close="closeHandle"
      :visible.sync="visible1">
      <el-upload
        drag
        :action="url"
        :before-upload="beforeUploadHandle"
        :on-success="successHandle"
        multiple
        style="text-align: center;">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只支持jpg、png、gif格式的图片！</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import ossUpload from '../oss/oss-upload.vue'
export default {
  data () {
    return {
      visible: false,
      visible1: false,
      url: '',
      num: 0,
      successNum: 0,
      uploadVisible: false,
      dataForm: {
        id: 0,
        image: '',
        num: '',
        status: '',
        createTime: ''
      },
      dataRule: {
        image: [
          { required: true, message: '轮播图片不能为空', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '序号不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态（0：不启用，1启用）不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    ossUpload
  },
  methods: {
    // 上传之前
    beforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif' && file.type !== 'image/webp') {
        this.$message.error('只支持jpg、png、gif格式的图片！')
        return false
      }
      this.num++
    },
    // 上传成功
    successHandle (response, file, fileList) {
      this.fileList = fileList
      console.log('file')
      this.dataForm.image = file.response.url
      console.log(file.response.url)
      this.successNum++
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.visible1 = false
        }
      } else {
        this.$message.error(response.msg)
      }
    },
    // 弹窗关闭时
    closeHandle () {
      this.$emit('refreshDataList')
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/oss/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log(data)
          // this.dataList = data.page.list
          // this.totalPage = data.page.totalCount
        } else {
          // this.dataList = []
          // this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    uploadHandle () {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.visible1 = true
      })
    },
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/generator/zbbchart/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.image = data.zbbChart.image
              this.dataForm.num = data.zbbChart.num
              this.dataForm.status = data.zbbChart.status
              this.dataForm.createTime = data.zbbChart.createTime
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/generator/zbbchart/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'image': this.dataForm.image,
              'num': this.dataForm.num,
              'status': this.dataForm.status,
              'createTime': this.dataForm.createTime
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                  this.dataForm.image = null
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
